#!/usr/bin/python
#coding: utf-8

from bs4 import BeautifulSoup
from Downloader.PageDownloader import *

class Bugzilla():
    def __init__(self, url=None,doc=None, bug_id=None, software=None):
        self.url = url
        self.doc = doc
        self.bugId = bug_id
        self.software = software
        self.bugInfo = {}

    def parse_doc(self):
        dic = {}
        soup = BeautifulSoup(self.doc)
        div = soup.find("div", id="bugzilla-body")
        h1 = div.find("h1")
        
        table = div.find("table", "bugfields")
        th_list = table.findAll("th")
        dict = {}

        for th in th_list:
            print th
            key = th.text[0:-1]
            if key == "Attachments":
                next_element = th.find_next()
            value = ""
            element = th.find_next()
            while (element.name == "td"):
                text = element.text
                value += element.text
                element = element.find_next()
            # value=html_parser.unescape(value)
            dict[key] = value

        for key in dict.keys():
            print key + ":" + dict[key]
        return dict

    def get_bug_information(self):
        if self.bugInfo is None or len(self.bugInfo.keys()) == 0:
            self.bugInfo['bugID'] = self.bugId
            self.bugInfo['software'] = self.software
            self.bugInfo['url'] = self.url
            self.bugInfo['detail'] = self.parse_doc()
        return self.bugInfo